package logic

import (
	"context"
	"fmt"
	"vipshop/cache"
	"vipshop/models"
	"vipshop/pkg"

	"vipshop/vipshoprpc/internal/svc"
	"vipshop/vipshoprpc/vipshoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 修改密码
func (l *UpdateLogic) Update(in *vipshoprpc.UpdateRequest) (*vipshoprpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line

	var user models.User
	models.DB.Debug().Where("account = ?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该账号不存在,修改失败")
	}

	if in.Password != in.NewPassword {
		return nil, fmt.Errorf("两次输入的密码不一致,修改失败")
	}

	if user.Password == pkg.Md5(in.NewPassword) {
		return nil, fmt.Errorf("新密码和原密码一致,修改失败")
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if result != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误,修改失败")
	}

	user.Password = pkg.Md5(in.Password)
	models.DB.Debug().Updates(&user)

	return &vipshoprpc.UpdateResponse{
		UserId: int64(user.ID),
	}, nil
}
